home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2009 February / PCWFEB09.iso / Software / Linux / Kubuntu 8.10 / kubuntu-8.10-desktop-i386.iso / casper / filesystem.squashfs / usr / lib / python2.5 / gzip.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2008-10-29  |  14KB  |  511 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.5)
  3.  
  4. """Functions that read and write gzipped files.
  5.  
  6. The user of the file doesn't have to worry about the compression,
  7. but random access is not allowed."""
  8. import struct
  9. import sys
  10. import time
  11. import zlib
  12. import __builtin__
  13. __all__ = [
  14.     'GzipFile',
  15.     'open']
  16. (FTEXT, FHCRC, FEXTRA, FNAME, FCOMMENT) = (1, 2, 4, 8, 16)
  17. (READ, WRITE) = (1, 2)
  18.  
  19. def U32(i):
  20.     """Return i as an unsigned integer, assuming it fits in 32 bits.
  21.  
  22.     If it's >= 2GB when viewed as a 32-bit unsigned int, return a long.
  23.     """
  24.     if i < 0:
  25.         i += 0x100000000L
  26.     
  27.     return i
  28.  
  29.  
  30. def LOWU32(i):
  31.     '''Return the low-order 32 bits of an int, as a non-negative int.'''
  32.     return i & 0xFFFFFFFFL
  33.  
  34.  
  35. def write32(output, value):
  36.     output.write(struct.pack('<l', value))
  37.  
  38.  
  39. def write32u(output, value):
  40.     output.write(struct.pack('<L', value))
  41.  
  42.  
  43. def read32(input):
  44.     return struct.unpack('<l', input.read(4))[0]
  45.  
  46.  
  47. def open(filename, mode = 'rb', compresslevel = 9):
  48.     """Shorthand for GzipFile(filename, mode, compresslevel).
  49.  
  50.     The filename argument is required; mode defaults to 'rb'
  51.     and compresslevel defaults to 9.
  52.  
  53.     """
  54.     return GzipFile(filename, mode, compresslevel)
  55.  
  56.  
  57. class GzipFile:
  58.     '''The GzipFile class simulates most of the methods of a file object with
  59.     the exception of the readinto() and truncate() methods.
  60.  
  61.     '''
  62.     myfileobj = None
  63.     max_read_chunk = 10485760
  64.     
  65.     def __init__(self, filename = None, mode = None, compresslevel = 9, fileobj = None):
  66.         """Constructor for the GzipFile class.
  67.  
  68.         At least one of fileobj and filename must be given a
  69.         non-trivial value.
  70.  
  71.         The new class instance is based on fileobj, which can be a regular
  72.         file, a StringIO object, or any other object which simulates a file.
  73.         It defaults to None, in which case filename is opened to provide
  74.         a file object.
  75.  
  76.         When fileobj is not None, the filename argument is only used to be
  77.         included in the gzip file header, which may includes the original
  78.         filename of the uncompressed file.  It defaults to the filename of
  79.         fileobj, if discernible; otherwise, it defaults to the empty string,
  80.         and in this case the original filename is not included in the header.
  81.  
  82.         The mode argument can be any of 'r', 'rb', 'a', 'ab', 'w', or 'wb',
  83.         depending on whether the file will be read or written.  The default
  84.         is the mode of fileobj if discernible; otherwise, the default is 'rb'.
  85.         Be aware that only the 'rb', 'ab', and 'wb' values should be used
  86.         for cross-platform portability.
  87.  
  88.         The compresslevel argument is an integer from 1 to 9 controlling the
  89.         level of compression; 1 is fastest and produces the least compression,
  90.         and 9 is slowest and produces the most compression.  The default is 9.
  91.  
  92.         """
  93.         if mode and 'b' not in mode:
  94.             mode += 'b'
  95.         
  96.         if fileobj is None:
  97.             if not mode:
  98.                 pass
  99.             fileobj = self.myfileobj = __builtin__.open(filename, 'rb')
  100.         
  101.         if filename is None:
  102.             if hasattr(fileobj, 'name'):
  103.                 filename = fileobj.name
  104.             else:
  105.                 filename = ''
  106.         
  107.         if mode is None:
  108.             if hasattr(fileobj, 'mode'):
  109.                 mode = fileobj.mode
  110.             else:
  111.                 mode = 'rb'
  112.         
  113.         if mode[0:1] == 'r':
  114.             self.mode = READ
  115.             self._new_member = True
  116.             self.extrabuf = ''
  117.             self.extrasize = 0
  118.             self.filename = filename
  119.             self.min_readsize = 100
  120.         elif mode[0:1] == 'w' or mode[0:1] == 'a':
  121.             self.mode = WRITE
  122.             self._init_write(filename)
  123.             self.compress = zlib.compressobj(compresslevel, zlib.DEFLATED, -(zlib.MAX_WBITS), zlib.DEF_MEM_LEVEL, 0)
  124.         else:
  125.             raise IOError, 'Mode ' + mode + ' not supported'
  126.         self.fileobj = fileobj
  127.         self.offset = 0
  128.         if self.mode == WRITE:
  129.             self._write_gzip_header()
  130.         
  131.  
  132.     
  133.     def __repr__(self):
  134.         s = repr(self.fileobj)
  135.         return '<gzip ' + s[1:-1] + ' ' + hex(id(self)) + '>'
  136.  
  137.     
  138.     def _init_write(self, filename):
  139.         if filename[-3:] != '.gz':
  140.             filename = filename + '.gz'
  141.         
  142.         self.filename = filename
  143.         self.crc = zlib.crc32('')
  144.         self.size = 0
  145.         self.writebuf = []
  146.         self.bufsize = 0
  147.  
  148.     
  149.     def _write_gzip_header(self):
  150.         self.fileobj.write('\x1f\x8b')
  151.         self.fileobj.write('\x08')
  152.         fname = self.filename[:-3]
  153.         flags = 0
  154.         if fname:
  155.             flags = FNAME
  156.         
  157.         self.fileobj.write(chr(flags))
  158.         write32u(self.fileobj, long(time.time()))
  159.         self.fileobj.write('\x02')
  160.         self.fileobj.write('\xff')
  161.         if fname:
  162.             self.fileobj.write(fname + '\x00')
  163.         
  164.  
  165.     
  166.     def _init_read(self):
  167.         self.crc = zlib.crc32('')
  168.         self.size = 0
  169.  
  170.     
  171.     def _read_gzip_header(self):
  172.         magic = self.fileobj.read(2)
  173.         if magic != '\x1f\x8b':
  174.             raise IOError, 'Not a gzipped file'
  175.         
  176.         method = ord(self.fileobj.read(1))
  177.         if method != 8:
  178.             raise IOError, 'Unknown compression method'
  179.         
  180.         flag = ord(self.fileobj.read(1))
  181.         self.fileobj.read(6)
  182.         if flag & FEXTRA:
  183.             xlen = ord(self.fileobj.read(1))
  184.             xlen = xlen + 256 * ord(self.fileobj.read(1))
  185.             self.fileobj.read(xlen)
  186.         
  187.         if flag & FNAME:
  188.             while True:
  189.                 s = self.fileobj.read(1)
  190.                 if not s or s == '\x00':
  191.                     break
  192.                     continue
  193.         
  194.         if flag & FCOMMENT:
  195.             while True:
  196.                 s = self.fileobj.read(1)
  197.                 if not s or s == '\x00':
  198.                     break
  199.                     continue
  200.         
  201.         if flag & FHCRC:
  202.             self.fileobj.read(2)
  203.         
  204.  
  205.     
  206.     def write(self, data):
  207.         if self.mode != WRITE:
  208.             import errno as errno
  209.             raise IOError(errno.EBADF, 'write() on read-only GzipFile object')
  210.         
  211.         if self.fileobj is None:
  212.             raise ValueError, 'write() on closed GzipFile object'
  213.         
  214.         if len(data) > 0:
  215.             self.size = self.size + len(data)
  216.             self.crc = zlib.crc32(data, self.crc)
  217.             self.fileobj.write(self.compress.compress(data))
  218.             self.offset += len(data)
  219.         
  220.  
  221.     
  222.     def read(self, size = -1):
  223.         if self.mode != READ:
  224.             import errno
  225.             raise IOError(errno.EBADF, 'read() on write-only GzipFile object')
  226.         
  227.         if self.extrasize <= 0 and self.fileobj is None:
  228.             return ''
  229.         
  230.         readsize = 1024
  231.         if size < 0:
  232.             
  233.             try:
  234.                 while True:
  235.                     self._read(readsize)
  236.                     readsize = min(self.max_read_chunk, readsize * 2)
  237.             except EOFError:
  238.                 size = self.extrasize
  239.             except:
  240.                 None<EXCEPTION MATCH>EOFError
  241.             
  242.  
  243.         None<EXCEPTION MATCH>EOFError
  244.         
  245.         try:
  246.             while size > self.extrasize:
  247.                 self._read(readsize)
  248.                 readsize = min(self.max_read_chunk, readsize * 2)
  249.         except EOFError:
  250.             if size > self.extrasize:
  251.                 size = self.extrasize
  252.             
  253.         except:
  254.             size > self.extrasize
  255.  
  256.         chunk = self.extrabuf[:size]
  257.         self.extrabuf = self.extrabuf[size:]
  258.         self.extrasize = self.extrasize - size
  259.         self.offset += size
  260.         return chunk
  261.  
  262.     
  263.     def _unread(self, buf):
  264.         self.extrabuf = buf + self.extrabuf
  265.         self.extrasize = len(buf) + self.extrasize
  266.         self.offset -= len(buf)
  267.  
  268.     
  269.     def _read(self, size = 1024):
  270.         if self.fileobj is None:
  271.             raise EOFError, 'Reached EOF'
  272.         
  273.         if self._new_member:
  274.             pos = self.fileobj.tell()
  275.             self.fileobj.seek(0, 2)
  276.             if pos == self.fileobj.tell():
  277.                 raise EOFError, 'Reached EOF'
  278.             else:
  279.                 self.fileobj.seek(pos)
  280.             self._init_read()
  281.             self._read_gzip_header()
  282.             self.decompress = zlib.decompressobj(-(zlib.MAX_WBITS))
  283.             self._new_member = False
  284.         
  285.         buf = self.fileobj.read(size)
  286.         if buf == '':
  287.             uncompress = self.decompress.flush()
  288.             self._read_eof()
  289.             self._add_read_data(uncompress)
  290.             raise EOFError, 'Reached EOF'
  291.         
  292.         uncompress = self.decompress.decompress(buf)
  293.         self._add_read_data(uncompress)
  294.         if self.decompress.unused_data != '':
  295.             self.fileobj.seek(-len(self.decompress.unused_data) + 8, 1)
  296.             self._read_eof()
  297.             self._new_member = True
  298.         
  299.  
  300.     
  301.     def _add_read_data(self, data):
  302.         self.crc = zlib.crc32(data, self.crc)
  303.         self.extrabuf = self.extrabuf + data
  304.         self.extrasize = self.extrasize + len(data)
  305.         self.size = self.size + len(data)
  306.  
  307.     
  308.     def _read_eof(self):
  309.         self.fileobj.seek(-8, 1)
  310.         crc32 = read32(self.fileobj)
  311.         isize = U32(read32(self.fileobj))
  312.         if U32(crc32) != U32(self.crc):
  313.             raise IOError, 'CRC check failed'
  314.         elif isize != LOWU32(self.size):
  315.             raise IOError, 'Incorrect length of data produced'
  316.         
  317.  
  318.     
  319.     def close(self):
  320.         if self.mode == WRITE:
  321.             self.fileobj.write(self.compress.flush())
  322.             write32u(self.fileobj, LOWU32(self.crc))
  323.             write32u(self.fileobj, LOWU32(self.size))
  324.             self.fileobj = None
  325.         elif self.mode == READ:
  326.             self.fileobj = None
  327.         
  328.         if self.myfileobj:
  329.             self.myfileobj.close()
  330.             self.myfileobj = None
  331.         
  332.  
  333.     
  334.     def __del__(self):
  335.         
  336.         try:
  337.             if self.myfileobj is None and self.fileobj is None:
  338.                 return None
  339.         except AttributeError:
  340.             return None
  341.  
  342.         self.close()
  343.  
  344.     
  345.     def flush(self, zlib_mode = zlib.Z_SYNC_FLUSH):
  346.         if self.mode == WRITE:
  347.             self.fileobj.write(self.compress.flush(zlib_mode))
  348.         
  349.         self.fileobj.flush()
  350.  
  351.     
  352.     def fileno(self):
  353.         """Invoke the underlying file object's fileno() method.
  354.  
  355.         This will raise AttributeError if the underlying file object
  356.         doesn't support fileno().
  357.         """
  358.         return self.fileobj.fileno()
  359.  
  360.     
  361.     def isatty(self):
  362.         return False
  363.  
  364.     
  365.     def tell(self):
  366.         return self.offset
  367.  
  368.     
  369.     def rewind(self):
  370.         '''Return the uncompressed stream file position indicator to the
  371.         beginning of the file'''
  372.         if self.mode != READ:
  373.             raise IOError("Can't rewind in write mode")
  374.         
  375.         self.fileobj.seek(0)
  376.         self._new_member = True
  377.         self.extrabuf = ''
  378.         self.extrasize = 0
  379.         self.offset = 0
  380.  
  381.     
  382.     def seek(self, offset):
  383.         if self.mode == WRITE:
  384.             if offset < self.offset:
  385.                 raise IOError('Negative seek in write mode')
  386.             
  387.             count = offset - self.offset
  388.             for i in range(count // 1024):
  389.                 self.write(1024 * '\x00')
  390.             
  391.             self.write((count % 1024) * '\x00')
  392.         elif self.mode == READ:
  393.             if offset < self.offset:
  394.                 self.rewind()
  395.             
  396.             count = offset - self.offset
  397.             for i in range(count // 1024):
  398.                 self.read(1024)
  399.             
  400.             self.read(count % 1024)
  401.         
  402.  
  403.     
  404.     def readline(self, size = -1):
  405.         if size < 0:
  406.             size = sys.maxint
  407.             readsize = self.min_readsize
  408.         else:
  409.             readsize = size
  410.         bufs = []
  411.         while size != 0:
  412.             c = self.read(readsize)
  413.             i = c.find('\n')
  414.             if (size <= i or i == -1) and len(c) > size:
  415.                 i = size - 1
  416.             
  417.             if i >= 0 or c == '':
  418.                 bufs.append(c[:i + 1])
  419.                 self._unread(c[i + 1:])
  420.                 break
  421.             
  422.             bufs.append(c)
  423.             size = size - len(c)
  424.             readsize = min(size, readsize * 2)
  425.         if readsize > self.min_readsize:
  426.             self.min_readsize = min(readsize, self.min_readsize * 2, 512)
  427.         
  428.         return ''.join(bufs)
  429.  
  430.     
  431.     def readlines(self, sizehint = 0):
  432.         if sizehint <= 0:
  433.             sizehint = sys.maxint
  434.         
  435.         L = []
  436.         while sizehint > 0:
  437.             line = self.readline()
  438.             if line == '':
  439.                 break
  440.             
  441.             L.append(line)
  442.             sizehint = sizehint - len(line)
  443.         return L
  444.  
  445.     
  446.     def writelines(self, L):
  447.         for line in L:
  448.             self.write(line)
  449.         
  450.  
  451.     
  452.     def __iter__(self):
  453.         return self
  454.  
  455.     
  456.     def next(self):
  457.         line = self.readline()
  458.         if line:
  459.             return line
  460.         else:
  461.             raise StopIteration
  462.  
  463.  
  464.  
  465. def _test():
  466.     args = sys.argv[1:]
  467.     if args:
  468.         pass
  469.     decompress = args[0] == '-d'
  470.     if decompress:
  471.         args = args[1:]
  472.     
  473.     if not args:
  474.         args = [
  475.             '-']
  476.     
  477.     for arg in args:
  478.         if decompress:
  479.             if arg == '-':
  480.                 f = GzipFile(filename = '', mode = 'rb', fileobj = sys.stdin)
  481.                 g = sys.stdout
  482.             elif arg[-3:] != '.gz':
  483.                 print "filename doesn't end in .gz:", repr(arg)
  484.                 continue
  485.             
  486.             f = open(arg, 'rb')
  487.             g = __builtin__.open(arg[:-3], 'wb')
  488.         elif arg == '-':
  489.             f = sys.stdin
  490.             g = GzipFile(filename = '', mode = 'wb', fileobj = sys.stdout)
  491.         else:
  492.             f = __builtin__.open(arg, 'rb')
  493.             g = open(arg + '.gz', 'wb')
  494.         while True:
  495.             chunk = f.read(1024)
  496.             if not chunk:
  497.                 break
  498.             
  499.             g.write(chunk)
  500.         if g is not sys.stdout:
  501.             g.close()
  502.         
  503.         if f is not sys.stdin:
  504.             f.close()
  505.             continue
  506.     
  507.  
  508. if __name__ == '__main__':
  509.     _test()
  510.  
  511.